package com.sifeng.test;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ReplacementOfDataSplitting
 * @Author yang_gsh
 * @Date 2019-3-27 13:15
 * @Description
 */
public class ReplacementOfDataSplitting {
    public static Map<String, Object> getMap(String excelPath) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();

        //读取文件
        InputStream iStream=new FileInputStream(excelPath);
        XSSFWorkbook wb = new XSSFWorkbook(iStream);
        XSSFSheet sheet = wb.getSheetAt(0);
        if (sheet == null) {
            return null;
        }

        for (int i = 0; i <= sheet.getLastRowNum(); i++)  {
            XSSFRow row = sheet.getRow(i);
            XSSFCell cell = row.getCell(0);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String cellString1 = cell.getStringCellValue();

            XSSFCell cell1 = row.getCell(1);
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String cellString2 = cell1.getStringCellValue();

            XSSFCell cell2 = row.getCell(2);
            cell2.setCellType(Cell.CELL_TYPE_STRING);
            String cellString3 = cell2.getStringCellValue();

            if(map.containsKey(cellString2)) {
                List<String> list = (List<String>) map.get(cellString2);
                list.add(cellString1 + "," + cellString2 + "," + cellString3);
                map.remove(cellString2);
                map.put(cellString2, list);
            } else {
                List<String> list = new ArrayList<String>();
                list.add(cellString1 + "," + cellString2 + "," + cellString3);
                map.put(cellString2, list);
            }
        }
        return map;
    }

    public static void writeContent(String filePath, String content) throws IOException {
        FileWriter writer = new FileWriter(filePath);
        writer.write(content);
        writer.flush();
        writer.close();
    }

    public static void main(String[] args) throws IOException {
        Map<String, Object> map = ReplacementOfDataSplitting.getMap("E:\\新建文件夹 (2)\\对Redis故障导致营销活动发奖失败的数据进行提取.xlsx");
        for (String key : map.keySet()) {
            List<String> list = (List<String>) map.get(key);
            StringBuilder content = new StringBuilder();
            for (String s : list) {
                content.append(s);
                content.append("\n");
            }

            ReplacementOfDataSplitting.writeContent("E:\\新建文件夹 (2)\\" + key + "_20190327_01.csv", content.toString());
        }
    }
}
